<?php
/**
 * Created by PhpStorm.
 * User: kinso
 * Date: 2017/1/3
 * Time: 下午3:26
 */

namespace common\storage;


use common\queue\QueueInterface;
use common\set\SetInterface;
use yii\base\Component;

class JobStorage extends Component implements StorageInterface
{

    /**
     * 队列实例
     * @var null|QueueInterface|SetInterface
     */
    private $storage = null;

    /**
     * 向存储中添加一个或多个元素
     *
     * @param $members (string|array) 需要添加的元素
     * @param $storage string 存储key
     * @return integer 被添加到集合中的新元素的数量
     */
    public function add($members, $storage)
    {
        $result = 0;
        if ($this->storage instanceof SetInterface) {
            $result = $this->storage->add($members, $storage);
        } elseif ($this->storage instanceof QueueInterface) {
            $result = $this->storage->push($members, $storage);
        }
        return $result;
    }

    /**
     * 移除并返回存储中的一个随机元素
     *
     * @param $storage string 存储key
     * @return string 移除的元素
     */
    public function pop($storage)
    {
        return $this->storage->pop($storage);
    }

    public function setStructure($structure)
    {
        if (strtoupper($structure) == 'SET') {
            $this->storage = \Yii::$app->set;
        } else if (strtoupper($structure) == 'QUEUE') {
            $this->storage = \Yii::$app->queue;
        }
    }
}